<template>
  <div class="page-container">
    <!-- 头部统计卡片 -->
    <div class="stat-cards">
      <a-row :gutter="16">
        <a-col :span="6" v-for="stat in statistics" :key="stat.title">
          <a-card class="stat-card">
            <div class="stat-content">
              <component :is="stat.icon" class="stat-icon" :class="stat.type" />
              <div class="stat-info">
                <div class="stat-value">{{ stat.value }}</div>
                <div class="stat-title">{{ stat.title }}</div>
              </div>
            </div>
          </a-card>
        </a-col>
      </a-row>
    </div>

    <!-- 数据源状态 -->
    <a-card class="status-card">
      <template #title>
        <div class="card-header">
          <span>数据源状态</span>
          <a-radio-group v-model:value="timeRange" button-style="solid">
            <a-radio-button value="day">今日</a-radio-button>
            <a-radio-button value="week">本周</a-radio-button>
            <a-radio-button value="month">本月</a-radio-button>
          </a-radio-group>
        </div>
      </template>
      <div class="chart-container">
        <v-chart class="chart" :option="statusChartOption" autoresize />
      </div>
    </a-card>

    <!-- 数据源列表 -->
    <a-card class="source-card">
      <template #title>
        <div class="card-header">
          <span>数据源列表</span>
          <div class="header-actions">
            <a-input-search
              v-model:value="searchText"
              placeholder="搜索数据源"
              style="width: 200px; margin-right: 16px"
              @search="onSearch"
            />
            <a-button type="primary" @click="showAddModal = true">
              <template #icon><plus-outlined /></template>
              添加数据源
            </a-button>
          </div>
        </div>
      </template>
      <a-table
        :columns="columns"
        :data-source="dataSourceList"
        :loading="loading"
        :pagination="{ pageSize: 10 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ record.status }}
            </a-tag>
          </template>
          <template v-if="column.key === 'syncStatus'">
            <a-progress
              :percent="record.syncProgress"
              :status="getSyncStatus(record.syncProgress)"
              size="small"
            />
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="showDetails(record)">
                <template #icon><search-outlined /></template>
                详情
              </a-button>
              <a-button type="link" @click="showSync(record)">
                <template #icon><sync-outlined /></template>
                同步
              </a-button>
              <a-button type="link" danger @click="showDelete(record)">
                <template #icon><delete-outlined /></template>
                删除
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 同步记录 -->
    <a-card class="sync-card">
      <template #title>
        <div class="card-header">
          <span>同步记录</span>
          <a-button type="link">
            <template #icon><history-outlined /></template>
            查看全部
          </a-button>
        </div>
      </template>
      <a-timeline>
        <a-timeline-item
          v-for="record in syncRecords"
          :key="record.id"
          :color="getSyncRecordColor(record.status)"
        >
          <div class="sync-record">
            <div class="sync-header">
              <span class="sync-title">{{ record.title }}</span>
              <span class="sync-time">{{ record.time }}</span>
            </div>
            <div class="sync-content">
              <div class="sync-source">{{ record.source }}</div>
              <div class="sync-desc">{{ record.description }}</div>
            </div>
          </div>
        </a-timeline-item>
      </a-timeline>
    </a-card>

    <!-- 添加数据源 Modal -->
    <a-modal
      v-model:open="showAddModal"
      title="添加数据源"
      @ok="handleAddDataSource"
      :confirm-loading="addLoading"
      @cancel="resetAddForm"
      ok-text="添加"
      cancel-text="取消"
    >
      <a-form
        :model="addForm"
        :rules="addRules"
        ref="addFormRef"
        label-col="{ span: 6 }"
        wrapper-col="{ span: 16 }"
        layout="horizontal"
      >
        <a-form-item label="名称" name="name" required>
          <a-input v-model:value="addForm.name" placeholder="请输入数据源名称" />
        </a-form-item>
        <a-form-item label="类型" name="type" required>
          <a-select v-model:value="addForm.type" placeholder="请选择类型">
            <a-select-option value="database">数据库</a-select-option>
            <a-select-option value="api">API</a-select-option>
            <a-select-option value="file">文件</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="addForm.type === 'database'" label="连接串" name="connStr" required>
          <a-input v-model:value="addForm.connStr" placeholder="请输入数据库连接串" />
        </a-form-item>
        <a-form-item v-if="addForm.type === 'api'" label="API地址" name="apiUrl" required>
          <a-input v-model:value="addForm.apiUrl" placeholder="请输入API地址" />
        </a-form-item>
        <a-form-item v-if="addForm.type === 'file'" label="文件路径" name="filePath" required>
          <a-input v-model:value="addForm.filePath" placeholder="请输入文件路径" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent,
  MarkLineComponent,
  MarkPointComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import {
  DatabaseOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  WarningOutlined,
  SearchOutlined,
  PlusOutlined,
  HistoryOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  DataZoomComponent,
  MarkLineComponent,
  MarkPointComponent
])

// 统计数据
const statistics = ref([
  {
    title: '数据源总数',
    value: '12',
    icon: DatabaseOutlined,
    type: 'primary'
  },
  {
    title: '同步中',
    value: '2',
    icon: SyncOutlined,
    type: 'processing'
  },
  {
    title: '同步成功',
    value: '8',
    icon: CheckCircleOutlined,
    type: 'success'
  },
  {
    title: '同步失败',
    value: '2',
    icon: WarningOutlined,
    type: 'error'
  }
])

// 时间范围选择
const timeRange = ref('day')

// 数据源状态图表配置
const statusChartOption = ref({
  tooltip: {
    trigger: 'axis',
    formatter: function(params) {
      let result = params[0].axisValue + '<br/>'
      params.forEach(param => {
        const color = param.color
        const value = param.value
        const seriesName = param.seriesName
        result += `<span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${color};"></span>`
        result += `${seriesName}: ${value}条<br/>`
      })
      return result
    }
  },
  legend: {
    data: ['数据量', '同步量', '失败量']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: ['8:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00']
  },
  yAxis: {
    type: 'value',
    name: '数据量'
  },
  series: [
    {
      name: '数据量',
      type: 'line',
      smooth: true,
      data: [120, 132, 101, 134, 90, 230, 210],
      markPoint: {
        data: [
          { type: 'max', name: '最大值' },
          { type: 'min', name: '最小值' }
        ]
      }
    },
    {
      name: '同步量',
      type: 'line',
      smooth: true,
      data: [110, 125, 95, 130, 85, 220, 200]
    },
    {
      name: '失败量',
      type: 'line',
      smooth: true,
      data: [5, 3, 2, 4, 2, 5, 3]
    }
  ]
})

// 表格列定义
const columns = [
  {
    title: '数据源名称',
    dataIndex: 'name',
    key: 'name',
    sorter: (a, b) => a.name.localeCompare(b.name)
  },
  {
    title: '类型',
    dataIndex: 'type',
    key: 'type',
    filters: [
      { text: '数据库', value: 'database' },
      { text: 'API', value: 'api' },
      { text: '文件', value: 'file' }
    ],
    onFilter: (value, record) => record.type === value
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    filters: [
      { text: '正常', value: 'normal' },
      { text: '同步中', value: 'syncing' },
      { text: '错误', value: 'error' }
    ],
    onFilter: (value, record) => record.status === value
  },
  {
    title: '同步进度',
    dataIndex: 'syncStatus',
    key: 'syncStatus'
  },
  {
    title: '最后同步',
    dataIndex: 'lastSync',
    key: 'lastSync',
    sorter: (a, b) => new Date(a.lastSync) - new Date(b.lastSync)
  },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
    width: 200
  }
]

// 数据源列表
const dataSourceList = ref([
  {
    key: '1',
    name: '生产数据库',
    type: 'database',
    status: 'normal',
    syncProgress: 100,
    lastSync: '2024-02-20 10:30'
  },
  {
    key: '2',
    name: '设备API',
    type: 'api',
    status: 'syncing',
    syncProgress: 65,
    lastSync: '2024-02-20 10:25'
  },
  {
    key: '3',
    name: '质量检测文件',
    type: 'file',
    status: 'error',
    syncProgress: 0,
    lastSync: '2024-02-20 09:15'
  }
])

// 同步记录
const syncRecords = ref([
  {
    id: 1,
    title: '数据同步成功',
    status: 'success',
    source: '生产数据库',
    description: '完成生产数据同步，共同步1000条记录',
    time: '10分钟前'
  },
  {
    id: 2,
    title: '同步失败',
    status: 'error',
    source: '质量检测文件',
    description: '文件格式错误，请检查文件格式',
    time: '1小时前'
  },
  {
    id: 3,
    title: '开始同步',
    status: 'processing',
    source: '设备API',
    description: '开始同步设备运行数据',
    time: '2小时前'
  }
])

// 搜索和加载状态
const searchText = ref('')
const loading = ref(false)

// 获取状态颜色
const getStatusColor = (status) => {
  const colors = {
    'normal': 'success',
    'syncing': 'processing',
    'error': 'error'
  }
  return colors[status] || 'default'
}

// 获取同步状态
const getSyncStatus = (progress) => {
  if (progress === 100) return 'success'
  if (progress === 0) return 'exception'
  return 'active'
}

// 获取同步记录颜色
const getSyncRecordColor = (status) => {
  const colors = {
    'success': 'green',
    'error': 'red',
    'processing': 'blue'
  }
  return colors[status] || 'blue'
}

// 搜索处理
const onSearch = (value) => {
  loading.value = true
  // 模拟搜索延迟
  setTimeout(() => {
    loading.value = false
  }, 500)
}

// 显示详情
const showDetails = (record) => {
  console.log('显示数据源详情:', record)
}

// 显示同步
const showSync = (record) => {
  console.log('显示同步界面:', record)
}

// 显示删除
const showDelete = (record) => {
  console.log('显示删除确认:', record)
}

// 添加数据源相关
const showAddModal = ref(false)
const addLoading = ref(false)
const addForm = ref({
  name: '',
  type: 'database',
  connStr: '',
  apiUrl: '',
  filePath: ''
})
const addRules = ref({
  name: [{ required: true, message: '请输入数据源名称' }],
  type: [{ required: true, message: '请选择数据源类型' }],
  connStr: [{ required: true, message: '请输入数据库连接串' }],
  apiUrl: [{ required: true, message: '请输入API地址' }],
  filePath: [{ required: true, message: '请输入文件路径' }]
})
const addFormRef = ref(null)

// 添加数据源处理
const handleAddDataSource = () => {
  addFormRef.value.validate().then(() => {
    addLoading.value = true
    setTimeout(() => {
      addLoading.value = false
      showAddModal.value = false
      // 构造新数据源对象
      const newSource = {
        key: Date.now().toString(),
        name: addForm.value.name,
        type: addForm.value.type,
        status: 'normal',
        syncProgress: 0,
        lastSync: '-',
      }
      dataSourceList.value = [newSource, ...dataSourceList.value]
      message.success('添加成功')
      resetAddForm()
    }, 500)
  }).catch(() => {
    addLoading.value = false
  })
}

// 重置添加表单
const resetAddForm = () => {
  addForm.value = {
    name: '',
    type: 'database',
    connStr: '',
    apiUrl: '',
    filePath: ''
  }
  addFormRef.value.resetFields()
}

// 模拟数据更新
onMounted(() => {
  // 这里可以添加实际的数据获取逻辑
})
</script>

<style lang="less" scoped>
.stat-cards {
  margin-bottom: 16px;
}

.stat-card {
  margin-bottom: 16px;
}

.stat-content {
  display: flex;
  align-items: center;
}

.stat-icon {
  font-size: 24px;
  margin-right: 12px;
  padding: 8px;
  border-radius: 8px;
  
  &.primary {
    color: #1890ff;
    background-color: rgba(24, 144, 255, 0.1);
  }
  
  &.success {
    color: #52c41a;
    background-color: rgba(82, 196, 26, 0.1);
  }
  
  &.processing {
    color: #1890ff;
    background-color: rgba(24, 144, 255, 0.1);
  }
  
  &.error {
    color: #ff4d4f;
    background-color: rgba(255, 77, 79, 0.1);
  }
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  line-height: 1.2;
}

.stat-title {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}

.status-card,
.source-card,
.sync-card {
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.chart-container {
  height: 300px;
}

.chart {
  height: 100%;
}

.sync-record {
  .sync-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  .sync-title {
    font-weight: bold;
  }

  .sync-time {
    color: rgba(0, 0, 0, 0.45);
    font-size: 12px;
  }

  .sync-content {
    .sync-source {
      color: #1890ff;
      margin-bottom: 4px;
    }

    .sync-desc {
      color: rgba(0, 0, 0, 0.65);
    }
  }
}
</style> 